//
//  HTClassImagePickerHelper.swift
//  QuitSmokingApp
//  
//  Created by wealon on 2024.
//  QuitSmokingApp.
//  
    

import Foundation
import MobileCoreServices
import UIKit
import UniformTypeIdentifiers

class HTClassImagePickerHelper: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    typealias BLOCK_ImagePickerCompletionHandlerBLOCK = ((UIImage?) -> Void)
    
    private var var_imagePickerCompletionHandler: BLOCK_ImagePickerCompletionHandlerBLOCK?
    private weak var var_presentingViewController: UIViewController?
    
    func ht_presentImagePicker(var_from var_viewController: UIViewController, var_sourceType: UIImagePickerController.SourceType, var_completionHandler: @escaping BLOCK_ImagePickerCompletionHandlerBLOCK) {
        self.var_imagePickerCompletionHandler = var_completionHandler
        self.var_presentingViewController = var_viewController
        
        if UIImagePickerController.isSourceTypeAvailable(var_sourceType) {
            let var_imagePickerController = UIImagePickerController()
            var_imagePickerController.sourceType = var_sourceType
            var_imagePickerController.delegate = self
            
            if var_sourceType == .camera {
                var_imagePickerController.mediaTypes = [UTType.image.identifier]
            }
            
            var_viewController.present(var_imagePickerController, animated: true, completion: nil)
        } else {
            print("Error: Source type \(var_sourceType) is not available.")
        }
    }
    
    // MARK: - UIImagePickerControllerDelegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        if let var_image = info[.originalImage] as? UIImage {
            self.var_imagePickerCompletionHandler?(var_image)
        } else {
            print("Error: Failed to retrieve image.")
            self.var_imagePickerCompletionHandler?(nil)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
        self.var_imagePickerCompletionHandler?(nil)
    }
}
